<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Tenant extends Model
{
    use HasFactory;

    public $incrementing = false;
    protected $keyType = 'string';

    public const STATUS_ACTIVE = 'active';
    public const STATUS_INACTIVE = 'inactive';
    public const STATUS_SUSPENDED = 'suspended';

    public const TYPE_INDIVIDUAL = 'individual';
    public const TYPE_ENTERPRISE = 'enterprise';

    protected $fillable = [
        'name',
        'company_name',
        'tax_registration_number',
        'address',
        'bank_name',
        'bank_account',
        'invoice_contact_phone',
        'invoice_mailing_address',
        'invoice_recipient',
        'database',
        'settings',
        'status',
        'contact_phone',
        'contact_email',
        'tenant_type',
        'service_fee_rate',
        'account_balance',
        'invoiceable_amount',
        'created_by',
    ];

    protected $casts = [
        'id' => 'string',
        'settings' => 'array',
        'account_balance' => 'decimal:2',
        'invoiceable_amount' => 'decimal:2',
        'service_fee_rate' => 'decimal:4',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function getIdAttribute($value): string
    {
        return (string) $value;
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = static::generateSnowflakeId();
            }
        });
    }

    public static function generateSnowflakeId(): string
    {
        $timestamp = (int) (microtime(true) * 1000);
        $machineId = mt_rand(0, 1023);
        $sequence = mt_rand(0, 4095);

        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;

        return (string) $snowflakeId;
    }

    /**
     * 租户用户
     */
    public function users()
    {
        return $this->hasMany(User::class);
    }

    /**
     * 租户专用用户
     */
    public function tenantUsers()
    {
        return $this->hasMany(TenantUser::class);
    }

    /**
     * 员工
     */
    public function employees()
    {
        return $this->hasMany(Employee::class);
    }

    /**
     * 任务
     */
    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

    /**
     * 交易记录
     */
    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    /**
     * 结算记录
     */
    public function settlements()
    {
        return $this->hasMany(Settlement::class);
    }

    /**
     * 开票记录
     */
    public function invoices()
    {
        return $this->hasMany(Invoice::class);
    }

    /**
     * 租户设置
     */
    public function tenantSettings()
    {
        return $this->hasMany(TenantSetting::class);
    }

    /**
     * 创建人（A端用户）
     */
    public function creator()
    {
        return $this->belongsTo(AdminUser::class, 'created_by');
    }

    /**
     * 身份切换日志
     */
    public function impersonationLogs()
    {
        return $this->hasMany(AdminImpersonationLog::class);
    }
}
